package com.example.question.list.list1;

/**
 * @Date 2023-07-05
 * @Author Jonathan
 * @link { <a href="https://leetcode.cn/problems/reverse-linked-list-ii/">...</a> }
 */
public class Code11_92 {
    private ListNode last;

    public static void main(String[] args) {
        ListNode listNode = List.createList(new int[]{1, 2, 3, 4, 5, 6});
        Code11_92 code = new Code11_92();
        ListNode node = code.reverseBetween(listNode, 2, 4);
        List.printLink(node);

    }

    /**
     * todo  考虑迭代的做法
     *
     * @param head
     * @param left
     * @param right
     * @return
     */
    public ListNode reverseBetween(ListNode head, int left, int right) {
        ListNode dummyHead = new ListNode(-1, head);
        process(dummyHead, left + 1, right + 1);
        return dummyHead.next;
    }


    public ListNode process(ListNode head, int left, int right) {
        if (right == 1) {
            last = head.next;
            return head;
        }

        ListNode ret = process(head.next, --left, --right);
        if (left <= 0 && right > 0) {
            head.next.next = head;
            head.next = null;
            return ret;
        } else if (left == 1) {
            head.next.next = last;
            head.next = ret;
            return head;
        } else {
            return head;
        }
    }
}
